/**
 * Created by Administrator on 2017/6/9.
 */

var GlobalConfig = require('../../config/config.json');
var mysql = require("mysql");

module.exports = {
    pool: null,
    format: mysql.format,
    escape: mysql.escape,

    init: function(callback) {
        if (!GlobalConfig.mysql.enable) {
            callback();
        }

        var options = {
            host : GlobalConfig.mysql.ip,
            port : GlobalConfig.mysql.port,
            user : GlobalConfig.mysql.user,
            password : GlobalConfig.mysql.password,
            charset: GlobalConfig.mysql.charset,
            database : GlobalConfig.mysql.database,
            insecureAuth: true,
        };

        this.pool = mysql.createPool(options);

        this.pool.getConnection(function(err, connection) {
            if (connection) {
                connection.release();
            }

            callback(err);
        });
    },

    /**
     * 执行SQL语句
     * @param sql
     * @param callback (err, results)
     */
    query: function(sql, callback) {
        if (!this.pool) {
            callback(null, []); return;
        }

        this.pool.query(sql, callback);
    },
}